<script setup lang="ts">
  import EditOrAddModuleForm from './EditOrAddModuleForm.vue'
  import { nextTick, ref, watch } from 'vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'

  const props = defineProps({
    mode: {
      type: String,
      default: () => 'edit',
    },
    title: {
      type: String,
      default: () => '编辑模块',
    },
    moduleId: {
      type: String,
      require: true,
    },
    visible: {
      type: Boolean,
      default: () => false,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'delete'): void
    (e: 'close'): void
    (e: 'updated'): void
  }>()

  // 编辑工单模块弹窗状态
  const modalVisible = ref(false)

  // form组件实例
  const editOrAddModuleFormRef = ref<InstanceType<typeof EditOrAddModuleForm> | null>(null)

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    if (editOrAddModuleFormRef.value) {
      const res = await editOrAddModuleFormRef.value.save()
      if (res) {
        emits('close')
        emits('updated')
      }
    }
  }

  watch(props, async (value) => {
    modalVisible.value = value.visible
    await nextTick()
    if (value.visible && editOrAddModuleFormRef.value) {
      await editOrAddModuleFormRef.value.getSlaRuleOptionsFn('')
    }
  })
</script>

<template>
  <HModal :model-value="modalVisible" :width="850" @close="$emit('close')">
    <template #header>
      <div class="my-header">
        <h3 class="title">{{ props.title }}</h3>
      </div>
    </template>
    <div v-loading="props.loading" element-loading-text="加载中...">
      <div class="form-text module-form">
        <EditOrAddModuleForm
          :mode="props.mode"
          :module-id="moduleId"
          ref="editOrAddModuleFormRef"
        />
      </div>
    </div>

    <template #footerLeft>
      <HPlainBgButton is-modal type="error" @click="$emit('delete')">删除</HPlainBgButton>
    </template>

    <template #footerRight>
      <HButton is-modal type="primary" @click="onConfirm">确定</HButton>
      <HButton is-modal @click="modalVisible = false">取消</HButton>
    </template>
  </HModal>
</template>

<style scoped lang="scss">
  .del-btn {
    width: 3vw;
    color: #fff;
    background-color: $deleteColor;
    border-color: $deleteColor;
  }

  .del-btn:hover {
    width: 3vw;
    color: #fff;
    background-color: rgba($deleteColor, 0.8);
    border-color: rgba($deleteColor, 0.8);
  }
</style>
